package com.lframework.xingyun.basedata.impl.product;

import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.lframework.starter.common.utils.Assert;
import com.lframework.starter.common.utils.CollectionUtil;
import com.lframework.starter.web.core.impl.BaseMpServiceImpl;
import com.lframework.xingyun.basedata.entity.ProductCostCard;
import com.lframework.xingyun.basedata.entity.ProductCostCardDetail;
import com.lframework.xingyun.basedata.mappers.ProductCostCardMapper;
import com.lframework.xingyun.basedata.service.product.ProductCostCardDetailService;
import com.lframework.xingyun.basedata.service.product.ProductCostCardService;
import com.lframework.xingyun.basedata.vo.product.costcard.CreateProductCostCardDetailVo;
import com.lframework.xingyun.basedata.vo.product.costcard.CreateProductCostCardVo;
import com.lframework.xingyun.basedata.vo.product.costcard.UpdateProductCostCardVo;
import java.util.List;
import java.util.stream.Collectors;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 商品成本卡服务实现
 *
 * @author zmj
 * @since 2024-01-01
 */
@Service
public class ProductCostCardServiceImpl extends BaseMpServiceImpl<ProductCostCardMapper, ProductCostCard>
    implements ProductCostCardService {

  @Autowired
  private ProductCostCardDetailService productCostCardDetailService;

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void create(CreateProductCostCardVo vo) {

    // 检查商品是否已有成本卡
    ProductCostCard existingCostCard = this.getByProductId(vo.getProductId());
    Assert.isNull(existingCostCard, "该商品已存在成本卡，不能重复创建！");

    // 创建成本卡
    ProductCostCard costCard = new ProductCostCard();
    costCard.setId(IdUtil.getSnowflake().nextIdStr());
    costCard.setProductId(vo.getProductId());
    costCard.setName(vo.getName());
    costCard.setDescription(vo.getDescription());
    costCard.setAvailable(vo.getAvailable());

    this.save(costCard);

    // 创建成本卡明细
    this.createDetails(costCard.getId(), vo.getDetails());
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void update(UpdateProductCostCardVo vo) {

    // 检查成本卡是否存在
    ProductCostCard costCard = this.getById(vo.getId());
    Assert.notNull(costCard, "成本卡不存在！");

    // 更新成本卡
    costCard.setName(vo.getName());
    costCard.setDescription(vo.getDescription());
    costCard.setAvailable(vo.getAvailable());

    this.updateById(costCard);

    // 删除原有明细
    productCostCardDetailService.deleteByCostCardId(vo.getId());

    // 创建新的明细（包括替换品）
    List<CreateProductCostCardDetailVo> createDetails = vo.getDetails().stream()
        .map(detail -> {
          CreateProductCostCardDetailVo createDetail = new CreateProductCostCardDetailVo();
          createDetail.setIngredientProductId(detail.getIngredientProductId());
          createDetail.setUnitId(detail.getUnitId());
          createDetail.setConsumeQuantity(detail.getConsumeQuantity());
          createDetail.setUnitCost(detail.getUnitCost());
          createDetail.setOrderNo(detail.getOrderNo());
          createDetail.setDescription(detail.getDescription());
          // 复制replacements
          if (detail.getReplacements() != null) {
            List<CreateProductCostCardDetailVo.ReplacementVo> repList = detail.getReplacements().stream().map(rep -> {
              CreateProductCostCardDetailVo.ReplacementVo repVo = new CreateProductCostCardDetailVo.ReplacementVo();
              repVo.setIngredientProductId(rep.getIngredientProductId());
              repVo.setUnitId(rep.getUnitId());
              repVo.setConsumeQuantity(rep.getConsumeQuantity());
              return repVo;
            }).collect(Collectors.toList());
            createDetail.setReplacements(repList);
          }
          return createDetail;
        }).collect(Collectors.toList());

    // 递归保存主成分和所有替换品
    this.createDetails(vo.getId(), createDetails);
  }

  @Override
  public ProductCostCard getByProductId(String productId) {

    LambdaQueryWrapper<ProductCostCard> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(ProductCostCard::getProductId, productId);
    wrapper.eq(ProductCostCard::getAvailable, true);

    return this.getOne(wrapper);
  }

  @Override
  public List<ProductCostCard> getByProductIds(List<String> productIds) {

    if (CollectionUtil.isEmpty(productIds)) {
      return CollectionUtil.emptyList();
    }

    LambdaQueryWrapper<ProductCostCard> wrapper = new LambdaQueryWrapper<>();
    wrapper.in(ProductCostCard::getProductId, productIds);
    wrapper.eq(ProductCostCard::getAvailable, true);

    return this.list(wrapper);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void delete(String id) {

    // 删除成本卡明细
    productCostCardDetailService.deleteByCostCardId(id);

    // 删除成本卡
    this.removeById(id);
  }

  @Override
  @Transactional(rollbackFor = Exception.class)
  public void deleteByProductId(String productId) {

    ProductCostCard costCard = this.getByProductId(productId);
    if (costCard != null) {
      this.delete(costCard.getId());
    }
  }

  /**
   * 创建成本卡明细
   *
   * @param costCardId
   * @param details
   */
  private void createDetails(String costCardId, List<CreateProductCostCardDetailVo> details) {

    if (CollectionUtil.isEmpty(details)) {
      return;
    }

    productCostCardDetailService.remove(Wrappers.lambdaUpdate(ProductCostCardDetail.class)
            .eq(ProductCostCardDetail::getCostCardId, costCardId));

    for (CreateProductCostCardDetailVo detail : details) {
      // 保存主成分
      ProductCostCardDetail entity = new ProductCostCardDetail();
      entity.setId(IdUtil.getSnowflake().nextIdStr());
      entity.setCostCardId(costCardId);
      entity.setIngredientProductId(detail.getIngredientProductId());
      entity.setUnitId(detail.getUnitId());
      entity.setConsumeQuantity(detail.getConsumeQuantity());
      entity.setUnitCost(detail.getUnitCost());
      entity.setOrderNo(detail.getOrderNo());
      entity.setDescription(detail.getDescription());
      // 主成分type=0
      entity.setType(0);
      // 计算总成本
      if (detail.getUnitCost() != null && detail.getConsumeQuantity() != null) {
        entity.setTotalCost(detail.getUnitCost().multiply(
            java.math.BigDecimal.valueOf(detail.getConsumeQuantity())));
      }
      productCostCardDetailService.save(entity);

      // 保存替换品
      if (detail.getReplacements() != null) {
        for (CreateProductCostCardDetailVo.ReplacementVo rep : detail.getReplacements()) {
          ProductCostCardDetail repEntity = new ProductCostCardDetail();
          repEntity.setId(IdUtil.getSnowflake().nextIdStr());
          repEntity.setCostCardId(costCardId);
          repEntity.setSourceProductId(entity.getIngredientProductId());
          repEntity.setIngredientProductId(rep.getIngredientProductId());
          repEntity.setUnitId(detail.getUnitId());
          repEntity.setConsumeQuantity(rep.getConsumeQuantity());
          // 替换品type=1
          repEntity.setType(1);
          productCostCardDetailService.save(repEntity);
        }
      }
    }
  }
} 